package com.maxdu.labs.stt.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.stt.R;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.maxdu.labs.stt.constants.Constants;
import com.maxdu.labs.stt.models.TPlan;
import com.maxdu.labs.stt.models.UserVSTPlan;
import com.maxdu.labs.stt.models.db.TPlanDBHelper;
import com.maxdu.labs.stt.models.db.UserVSTPlanDBHelper;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;

public class PendingTPlanRequestsActivity extends Activity {

	private TextView noPendingRequestTV;
	private ListView pendingRequestLV;
	private List<TPlan> pendingTrainings;
	
	private ProgressBar spinner;
	private PendingTrainingRequestAdapter adapter;
	
	private String currentUserId;
	
	private List<ParseObject> userVSTrainingPOs;
	
	private UiLifecycleHelper uiHelper;
	private Session.StatusCallback callback = new Session.StatusCallback() {
	    @Override
	    public void call(final Session session, final SessionState state, final Exception exception) {
	        onSessionStateChange(session, state, exception);
	    }
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_pending_training_request);
		
		Log.w(Constants.LOG_TAG, "About to launch Session.openActiveSession()");
		Session.openActiveSession(this, true, new Session.StatusCallback() {
		    @Override
		    public void call(Session session, SessionState state, Exception exception) {
		        if(session.isOpened()) {
		            Log.w(Constants.LOG_TAG, "FB session opened successfully");
		        } else {
		        	if(exception != null){
		        		Log.w(Constants.LOG_TAG, "FB session not opened ... " + exception.toString());
		        	}
		        }
		    }
		});
		
	    noPendingRequestTV = (TextView) findViewById(R.id.tv_no_training_request);
	    noPendingRequestTV.setVisibility(View.GONE);
	    
	    pendingRequestLV = (ListView) findViewById(R.id.list_pending_request);
	    
	    
	    spinner = (ProgressBar)findViewById(R.id.progressBar1);
	    spinner.setVisibility(View.GONE);
	    
	    uiHelper = new UiLifecycleHelper(this, callback);
	    uiHelper.onCreate(savedInstanceState);
        
	    userVSTrainingPOs = new ArrayList<ParseObject>();
	    pendingTrainings = new ArrayList<TPlan>();
        adapter = new PendingTrainingRequestAdapter(getApplicationContext(), R.layout.row_training_request, pendingTrainings);
		pendingRequestLV.setAdapter(adapter);
	    
	    // Check for an open session
	    Session session = Session.getActiveSession();
	    if (session != null && session.isOpened()) {
	    	
	        // Get the user's data
	        makeMeRequest(session);
	    }
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
	    super.onSaveInstanceState(outState);
	    uiHelper.onSaveInstanceState(outState);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    uiHelper.onActivityResult(requestCode, resultCode, data);
	    
	    // Check for an open session
	    Session session = Session.getActiveSession();
	    if (session != null && session.isOpened()) {
	    	
	        // Get the user's data
	        makeMeRequest(session);
	    }
	}
	
	private void makeMeRequest(final Session session) {
	    // Make an API call to get user data and define a 
	    // new callback to handle the response.
	    Request request = Request.newMeRequest(session, 
	            new Request.GraphUserCallback() {
	        @Override
	        public void onCompleted(GraphUser user, Response response) {
	            // If the response is successful
	            if (session == Session.getActiveSession()) {
	                if (user != null) {
	                    
	                	currentUserId = user.getId();
	                	
	            	    GetMyTrainingsTask task = new GetMyTrainingsTask();
	            	    task.execute(user.getId());
	                }
	            }
	            if (response.getError() != null) {
	                // Handle errors, will do so later.
	            }
	        }
	    });
	    request.executeAsync();
	} 
	
	private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
	    if (session != null && session.isOpened()) {
	        // Get the user's data.
	        makeMeRequest(session);
	    }
	}
	
	
	private class GetMyTrainingsTask extends AsyncTask<String, Void, List<TPlan>> {

	    @Override
		protected void onPreExecute() {
			super.onPreExecute();
			spinner.setVisibility(View.VISIBLE);
		}
		
		@Override
	    protected List<TPlan> doInBackground(String... userIds) {

	    	if (userIds != null){
	    		
	    		ParseQuery<ParseObject> query = ParseQuery.getQuery(UserVSTPlanDBHelper.PARSE_DB_TABLENAME_USERVSTPLAN);
	    		query.whereEqualTo(UserVSTPlanDBHelper.PARSE_DB_FIELD_USERID, userIds[0]);
	    		query.whereEqualTo(UserVSTPlanDBHelper.PARSE_DB_FIELD_ACCEPTED, UserVSTPlan.INVITATION_PENDING);
	    		
	    		query.findInBackground(new FindCallback<ParseObject>() {
	    		    public void done(List<ParseObject> trainingRequests, ParseException e) {
	    		        if (e == null) {
	    		        	if (trainingRequests != null && trainingRequests.size()> 0){
	    		        		Log.w(Constants.LOG_TAG,"--------- trainingRequests size === "+ trainingRequests.size());
	    		        		for (final ParseObject userVSTrainingPO : trainingRequests){

	    		    	    		ParseQuery<ParseObject> query = ParseQuery.getQuery(TPlanDBHelper.PARSE_DB_TABLENAME_TPLAN);
	    		    	    		query.whereEqualTo(TPlanDBHelper.PARSE_DB_FIELD_TPLANID, userVSTrainingPO.getString(UserVSTPlanDBHelper.PARSE_DB_FIELD_TPLANID));
	    		    	    		
	    		    	    		query.findInBackground(new FindCallback<ParseObject>() {
	    		    	    		    public void done(List<ParseObject> trainings, ParseException e) {
	    		    	    		        if (e == null) {
	    		    	    		        	if (trainings != null && trainings.size()> 0){
	    		    	    		        		for (ParseObject trainingPO : trainings){
	    		    	    		        			TPlan tplan = new TPlan(trainingPO.getString(TPlanDBHelper.PARSE_DB_FIELD_TPLANID),
	    		    	    		        												trainingPO.getString(TPlanDBHelper.PARSE_DB_FIELD_NAME),
	    		    	    		        												trainingPO.getInt(TPlanDBHelper.PARSE_DB_FIELD_TYPE1),
	    		    	    		        												trainingPO.getInt(TPlanDBHelper.PARSE_DB_FIELD_DURATION),
	    		    	    		        												trainingPO.getInt(TPlanDBHelper.PARSE_DB_FIELD_FREQUENCY1));
	    		    	    		    	    		pendingTrainings.add(tplan);
	    		    	    		    	    		userVSTrainingPOs.add(userVSTrainingPO);
	    		    	    		        		}
	    		    	    		        		adapter.notifyDataSetChanged();
	    		    	    		        		spinner.setVisibility(View.GONE);
	    		    	    		        	} else {
	    		    	    		        		Log.d(Constants.LOG_TAG, "we couldn't retrieve the pending FriendRequests for the current user: users list is EMPTY");
	    		    	    		        		spinner.setVisibility(View.GONE);
	    		    	    		        		noPendingRequestTV.setVisibility(View.VISIBLE);
	    		    	    		        	}
	    		    	    		        } else {
	    		    	    		            Log.d(Constants.LOG_TAG, "Error: " + e.getMessage());
	    		    	    		        }
	    		    	    		    }
	    		    	    		});
	    		        		}
	    		        		Log.d(Constants.LOG_TAG, "GetMyTrainingsTask::we successfully retrieved [" + pendingTrainings.size()+"] pending Trainings for the user: " + trainingRequests.get(0).getString(UserVSTPlanDBHelper.PARSE_DB_FIELD_USERID));
	    		        		adapter.notifyDataSetChanged();
	    		        		spinner.setVisibility(View.GONE);
	    		        		
	    		        	}else if(trainingRequests == null){
	    		        		Log.d(Constants.LOG_TAG, "we couldn't retrieve the pending FriendRequests for the current user: users list is NULL");
	    		        	}else{
	    		        		Log.d(Constants.LOG_TAG, "we couldn't retrieve the pending FriendRequests for the current user: users list is EMPTY");
	    		        		spinner.setVisibility(View.GONE);
	    		        		noPendingRequestTV.setVisibility(View.VISIBLE);
	    		        		
	    		        	}
	    		        } else {
	    		            Log.d(Constants.LOG_TAG, "Error: " + e.getMessage());
	    		        }
	    		    }
	    		});
	    		
	    		return pendingTrainings;
	    	}
	    	return null;
	    	
	    }
	}
	
	private class PendingTrainingRequestAdapter extends ArrayAdapter<TPlan>{

		List<TPlan> tplans;
		
		public PendingTrainingRequestAdapter(Context context, int resource,
				List<TPlan> objects) {
			super(context, resource, objects);
			
			tplans = objects;
		}
		
		@Override
	    public View getView(final int position, View convertView, ViewGroup parent) {
	        View view = convertView;
	        if (view == null) {
	        	LayoutInflater inflater = (LayoutInflater)getContext().getSystemService
	        		      (Context.LAYOUT_INFLATER_SERVICE);
	            view = inflater.inflate(R.layout.row_training_request, parent,false);
	        }

	        final TPlan tplan = tplans.get(position);
	        
	        
            TextView nameTextV = (TextView) view.findViewById(R.id.tv_training_name);
            Button btnAccept = (Button)view.findViewById(R.id.btn_accept);

            btnAccept.setOnClickListener(new OnClickListener() {
		      	  @Override
		      	  public void onClick(View v) {
		      		Toast.makeText(PendingTPlanRequestsActivity.this, "Request accepted",
		      				Toast.LENGTH_LONG).show();
		      		
		      		if(currentUserId != null){
		      			acceptThisTraining(userVSTrainingPOs.get(position));
		      		}
		      		pendingTrainings.remove(position);
		      		adapter.notifyDataSetChanged();
		      		
		      	  }
		      	});
            
            nameTextV.setText(tplan.getName());
	        
	        return view;
	    }
	}
	private void acceptThisTraining(final ParseObject parseObject){
		
		ParseObject object = ParseObject.createWithoutData(UserVSTPlanDBHelper.PARSE_DB_TABLENAME_USERVSTPLAN, parseObject.getObjectId());

		// Set a new value on quantity
		object.put(UserVSTPlanDBHelper.PARSE_DB_FIELD_ACCEPTED, UserVSTPlan.INVITATION_ACCEPTED);

		// Save
		object.saveInBackground(new SaveCallback() {
		  public void done(ParseException e) {
		    if (e == null) {
		    	Log.d(Constants.LOG_TAG,"we successfully updated the userVSTraining object with trainingId = [" 
		    			+ parseObject.getString(UserVSTPlanDBHelper.PARSE_DB_FIELD_TPLANID) + "] and userId = [" 
		    			+ parseObject.getString(UserVSTPlanDBHelper.PARSE_DB_FIELD_USERID) + "]");
		    } else {
		    	Log.e(Constants.LOG_TAG,"we couldn't update the userVSTraining object with trainingId = [" 
		    			+ parseObject.getString(UserVSTPlanDBHelper.PARSE_DB_FIELD_TPLANID) + "] and userId = [" 
		    			+ parseObject.getString(UserVSTPlanDBHelper.PARSE_DB_FIELD_USERID) + "]. error: " + e);
		    }
		  }
		});
	}
}
